﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;

namespace MysqlTest
{
    [ApiController]
    [Route("api/[controller]")]

    class OrderController
    {

            private readonly OrdersContext orderDb;

            public OrderController(OrdersContext context)
            {
                this.orderDb = context;


            }

        //查询订单
        [HttpGet]
        public ActionResult<List<Order>> SelectOrders(string customerName)
        {
            IQueryable<Order> query = orderDb.orders;
            if (customerName != null)
            {
                query = query.Where(t => t.CustomerName == customerName);
            }
            return query.ToList();
        }

        //根据订单号查询订单
        [HttpGet("{orderID}")]
        public ActionResult<Order> SelectOrdersByOrderCode(long orderID)
        {
            Order item = orderDb.orders.FirstOrDefault(o => o.OrderID == orderID);
            if (item == null)
            {
                return NotFound();
            }
            return item;
        }

        //添加订单
        [HttpPost]
            public ActionResult<Order> AddOrder(Order newOrder)
            {
                try
                {
                    orderDb.orders.Add(newOrder);
                    orderDb.SaveChanges();
                }
                catch (Exception e)
                {
                    return BadRequest(e.InnerException.Message;);
                }
                return newOrder;
            }

        //修改订单
        [HttpPut("{orderID}")]
        public ActionResult<Order> UpdateOrder(long orderID, Order updateOrder)
        {
            if (orderID != updateOrder.OrderID) return BadRequest("无法匹配");
            try
            {
                orderDb.Entry(updateOrder).State = EntityState.Modified;
                orderDb.SaveChanges();
            }
            catch (Exception e)
            {
                return BadRequest(e.InnerException.Message;);
            }
            return NoContent();
        }

        //根据订单号删除订单
        [HttpDelete("{orderID}")]
            public ActionResult<Order> DeleteOrder(long orderID)
            {
                try
                {
                    Order item = orderDb.orders.FirstOrDefault(o => o.OrderID == orderID);
                    if (item != null)
                    {
                        orderDb.orders.Remove(item);
                        orderDb.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    return BadRequest(e.InnerException.Message;);
                }
                return NoContent();
            }





           
        }
    }

